<script setup lang="ts">
import { ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import { fetchCheckTenantCode, fetchCreateTenant, fetchUpdateTenant } from '@/service/api';
import { enableStatusRecord } from '@/constants/business';
import { $t } from '@/locales';

interface Props {
  operateType: 'add' | 'edit';
  editingData: Api.SystemManage.Tenant | null;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (e: 'success'): void;
}>();

const visible = defineModel<boolean>('open', {
  default: false
});

const formRef = ref();
const loading = ref(false);
const checkingCode = ref(false);

const formModel = ref<Api.SystemManage.TenantDTO>({
  tenantCode: '',
  tenantName: '',
  description: '',
  contactName: '',
  contactPhone: '',
  contactEmail: '',
  tenantAddress: '',
  tenantDomain: '',
  expireTime: '',
  status: '1'
});

const statusOptions = [
  { label: $t(enableStatusRecord['1']), value: '1' },
  { label: $t(enableStatusRecord['2']), value: '2' }
];

const rules = {
  tenantCode: [
    { required: true, message: '请输入租户编码', trigger: 'blur', type: 'string' },
    { min: 2, max: 50, message: '租户编码长度在2-50个字符', trigger: 'blur', type: 'string' }
  ],
  tenantName: [
    { required: true, message: '请输入租户名称', trigger: 'blur', type: 'string' },
    { min: 2, max: 100, message: '租户名称长度在2-100个字符', trigger: 'blur', type: 'string' }
  ],
  contactName: [{ required: true, message: '请输入联系人', trigger: 'blur', type: 'string' }],
  contactPhone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur', type: 'string' }],
  contactEmail: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
  tenantDomain: [
    {
      pattern: /^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/,
      message: '请输入正确的域名',
      trigger: 'blur',
      type: 'string'
    }
  ],
  expireTime: [{ message: '请选择过期时间', trigger: 'change', type: 'string' }]
} as any;

watch(
  () => visible.value,
  val => {
    if (val) {
      if (props.operateType === 'edit' && props.editingData) {
        formModel.value = { ...props.editingData };
      } else {
        resetForm();
      }
    }
  }
);

function resetForm() {
  formModel.value = {
    tenantCode: '',
    tenantName: '',
    description: '',
    contactName: '',
    contactPhone: '',
    contactEmail: '',
    tenantAddress: '',
    tenantDomain: '',
    expireTime: '',
    status: '1'
  };
  formRef.value?.clearValidate();
}

async function handleSubmit() {
  try {
    await formRef.value?.validate();
    loading.value = true;

    if (props.operateType === 'add') {
      await fetchCreateTenant(formModel.value);
      message.success('创建成功');
    } else {
      await fetchUpdateTenant(props.editingData!.id, formModel.value);
      message.success('更新成功');
    }

    emit('success');
    handleClose();
  } catch (error: any) {
    if (error?.message) {
      message.error(error.message);
    }
  } finally {
    loading.value = false;
  }
}

async function handleCheckCode() {
  if (!formModel.value.tenantCode) return;

  try {
    checkingCode.value = true;
    const exists = await fetchCheckTenantCode(formModel.value.tenantCode);
    if (exists) {
      message.warning('租户编码已存在');
    } else {
      message.success('租户编码可用');
    }
  } catch {
    message.error('检查失败');
  } finally {
    checkingCode.value = false;
  }
}

function handleClose() {
  visible.value = false;
  resetForm();
}
</script>

<template>
  <ADrawer
    v-model:open="visible"
    :title="operateType === 'add' ? '新增租户' : '编辑租户'"
    width="600px"
    @close="handleClose"
  >
    <AForm ref="formRef" :model="formModel" :rules="rules" layout="vertical" @finish="handleSubmit">
      <ARow :gutter="16">
        <ACol :span="12">
          <AFormItem label="租户编码" name="tenantCode">
            <AInput
              v-model:value="formModel.tenantCode"
              placeholder="请输入租户编码"
              :disabled="operateType === 'edit'"
            >
              <template #suffix>
                <AButton
                  v-if="operateType === 'add'"
                  type="link"
                  size="small"
                  :loading="checkingCode"
                  @click="handleCheckCode"
                >
                  检查
                </AButton>
              </template>
            </AInput>
          </AFormItem>
        </ACol>
        <ACol :span="12">
          <AFormItem label="租户名称" name="tenantName">
            <AInput v-model:value="formModel.tenantName" placeholder="请输入租户名称" />
          </AFormItem>
        </ACol>
      </ARow>

      <AFormItem label="租户描述" name="description">
        <ATextarea v-model:value="formModel.description" placeholder="请输入租户描述" :rows="3" />
      </AFormItem>

      <ARow :gutter="16">
        <ACol :span="8">
          <AFormItem label="联系人" name="contactName">
            <AInput v-model:value="formModel.contactName" placeholder="请输入联系人" />
          </AFormItem>
        </ACol>
        <ACol :span="8">
          <AFormItem label="联系电话" name="contactPhone">
            <AInput v-model:value="formModel.contactPhone" placeholder="请输入联系电话" />
          </AFormItem>
        </ACol>
        <ACol :span="8">
          <AFormItem label="联系邮箱" name="contactEmail">
            <AInput v-model:value="formModel.contactEmail" placeholder="请输入联系邮箱" />
          </AFormItem>
        </ACol>
      </ARow>

      <AFormItem label="租户地址" name="tenantAddress">
        <ATextarea v-model:value="formModel.tenantAddress" placeholder="请输入租户地址" :rows="2" />
      </AFormItem>

      <ARow :gutter="16">
        <ACol :span="12">
          <AFormItem label="租户域名" name="tenantDomain">
            <AInput v-model:value="formModel.tenantDomain" placeholder="请输入租户域名" />
          </AFormItem>
        </ACol>
        <ACol :span="12">
          <AFormItem label="过期时间" name="expireTime">
            <ADatePicker
              v-model:value="formModel.expireTime"
              placeholder="请选择过期时间"
              style="width: 100%"
              :show-time="true"
              format="YYYY-MM-DD HH:mm:ss"
            />
          </AFormItem>
        </ACol>
      </ARow>

      <AFormItem label="状态" name="status">
        <ASelect v-model:value="formModel.status" placeholder="请选择状态" :options="statusOptions" />
      </AFormItem>
    </AForm>

    <template #footer>
      <div class="flex justify-end gap-8px">
        <AButton @click="handleClose">取消</AButton>
        <AButton type="primary" :loading="loading" @click="handleSubmit">
          {{ operateType === 'add' ? '创建' : '更新' }}
        </AButton>
      </div>
    </template>
  </ADrawer>
</template>
